/* eslint-disable react/no-array-index-key */
import NavBar from '@/components/Global/NavBar'
import classNames from 'classnames'
import { useEffect, useState } from 'react'
import { history } from 'umi'
import { fetchEvaluateResult, fetchClassDetail } from '../api'
import styles from './index.module.less'
import { RateQuestion } from './components/RateQuestion'
import { TeacherRateQuestion } from './components/TeacherRateQuestion'
import { SingleChoiceQuestion } from './components/SingleChoiceQuestion'
import { QnAQuestion } from './components/QnAQuestion'
import { Modal, TabBar } from 'antd-mobile'
import type { EvaluateResult } from './interface'
import type { ClassDetail } from '../index/interface'
import { EvaluateCategory } from '../enum'
import { QnADetail } from './components/QnADetail'
import { SingleChoiceDetail } from './components/SingleChoiceDetail'
import { QuestionTypeEnum } from '../write/enum'
import { MultiChoiceQuestion } from './components/MultiChoiceQuestion'
import { MultiChoiceDetail } from './components/MultiChoiceDetail'
import { stores } from '@/stores'

/** 获取问答题标题可见状态 */
const getQATitleVisible = (category: EvaluateCategory) => {
    // 部中心角色 & 互评报告
    if (category === EvaluateCategory.MutualReport && stores.userStore.isCenterRole) {
        return true
    }

    // 活动报告 | 授课意见表
    if ([EvaluateCategory.ActivityReport, EvaluateCategory.CourseOpinion].includes(category)) {
        return true
    }

    return false
}

export const EvaluateDetail = () => {
    const historyQuery = history.location.query as {
        groupId: string
        evaluateId: string
        listId: string
    }
    // 班级ID
    const groupId = Number(historyQuery.groupId)
    // 评价表ID
    const evaluateId = Number(historyQuery.evaluateId)
    // 表单ID
    const listId = Number(historyQuery.listId)

    const [classData, setClassData] = useState<ClassDetail>()
    const [evaluateData, setEvaluateData] = useState<EvaluateResult>()

    // 当前的题目索引
    const [currentQuestionIndex, setCurrentQuestionIndex] = useState<number>(0)

    useEffect(() => {
        const initClassData = async () => {
            const { data } = await fetchClassDetail(groupId)
            setClassData(data)
        }
        const initEvaluateData = async () => {
            const { data } = await fetchEvaluateResult(groupId, evaluateId, listId)
            setEvaluateData(data)

            // 培训师只能查看自己的评估详情
            if (stores.userStore.isTeacherRole) {
                const questionIndex = data.questions.findIndex(
                    it => it.user_id === stores.userStore.getUserInfo?.uid,
                )
                setCurrentQuestionIndex(questionIndex < 0 ? 0 : questionIndex)
            }
        }
        initClassData()
        initEvaluateData()
    }, [groupId, evaluateId, listId])

    // 是否已评分
    const hasScore = false

    // 除培训师外其他角色可切换查看不同培训师的互评报告
    const showTeacherTabBar =
        (evaluateData?.questions.length ?? 0) > 1 && !stores.userStore.isTeacherRole

    return (
        <div>
            <NavBar title="评估详情" />
            <div className={styles.page}>
                <div className={styles.headerBox}>
                    <div className={styles.header}>
                        <div className={styles.classInfo}>
                            <div>{classData?.name || '-'}</div>
                            <div>{`${classData?.begin_date || '-'} 至 ${
                                classData?.end_date || '-'
                            }`}</div>
                        </div>
                        <div
                            className={classNames(styles.score, {
                                [styles.score_fenshu]: hasScore,
                                [styles.score_wufenshu]: !hasScore,
                            })}
                        >
                            {/* {66} */}
                        </div>
                    </div>

                    <div className={styles.header_expand}>
                        <div className={styles.title}>{evaluateData?.title || '-'}</div>

                        <div className={styles.detail}>
                            {evaluateData?.lesson_name && (
                                <div>
                                    <span>教学内容：</span>
                                    <span>{evaluateData.lesson_name}</span>
                                </div>
                            )}
                            <div>
                                <span>发布时间：</span>
                                <span>{evaluateData?.release_time || '-'}</span>
                            </div>
                            <div>
                                <span>培训师：</span>
                                <span>{`${
                                    classData?.teacher_dispatch
                                        .map(item => item.realname)
                                        .join('、') || '-'
                                }`}</span>
                            </div>
                        </div>
                    </div>
                </div>

                {showTeacherTabBar && (
                    <div className={styles.teacherTab}>
                        <TabBar
                            defaultActiveKey={'0'}
                            onChange={key => {
                                setCurrentQuestionIndex(Number(key))
                            }}
                        >
                            {evaluateData?.questions.map((item, index) => (
                                <TabBar.Item key={index} title={item.teacher_name || '培训师'} />
                            ))}
                        </TabBar>
                    </div>
                )}

                {evaluateData?.questions[currentQuestionIndex].data.map(item => {
                    return (
                        <div key={item.id}>
                            {item.category === QuestionTypeEnum.SingleChoice && (
                                <SingleChoiceQuestion
                                    title={item.name}
                                    score={item.avg_score ?? 0}
                                    onViewDetail={() => {
                                        Modal.show({
                                            content: (
                                                <SingleChoiceDetail
                                                    title={item.name}
                                                    options={item.options}
                                                />
                                            ),
                                            closeOnMaskClick: true,
                                        })
                                    }}
                                />
                            )}

                            {item.category === QuestionTypeEnum.MultiChoice && (
                                <MultiChoiceQuestion
                                    title={item.name}
                                    score={item.avg_score ?? 0}
                                    onViewDetail={() => {
                                        Modal.show({
                                            content: (
                                                <MultiChoiceDetail
                                                    title={item.name}
                                                    options={item.options}
                                                />
                                            ),
                                            closeOnMaskClick: true,
                                        })
                                    }}
                                />
                            )}

                            {item.category === QuestionTypeEnum.QA && (
                                <QnAQuestion
                                    title={item.name}
                                    onViewDetail={() => {
                                        Modal.show({
                                            content: (
                                                <QnADetail
                                                    titleVisible={getQATitleVisible(
                                                        evaluateData.category,
                                                    )}
                                                    options={item.options}
                                                />
                                            ),
                                            closeOnMaskClick: true,
                                        })
                                    }}
                                />
                            )}

                            {item.category === QuestionTypeEnum.Rate && (
                                <RateQuestion title={item.name} options={item.options} />
                            )}

                            {item.category === QuestionTypeEnum.TeacherRate && (
                                <TeacherRateQuestion
                                    title={item.name}
                                    options={item.options}
                                    avg_score={item.avg_score ?? 0}
                                    isLeader={Boolean(item.is_leader)}
                                    teacherName={item.teacher_name || '-'}
                                />
                            )}
                        </div>
                    )
                })}
            </div>
        </div>
    )
}

export default EvaluateDetail
